import re
import pandas as pd
import tiktoken
from collections import OrderedDict
import langid
import concurrent.futures

import numpy as np
pd.set_option('display.max_rows', None)  # 设置显示最大行数为无限
pd.set_option('display.max_columns', None)  # 设置显示最大列数为无限
pd.set_option('display.max_colwidth', None)  # 设置最大列宽为无限

from Searcher.llm import super_eval
from Searcher.llm import llmglm as llm_thought
from Searcher.llm import llm


class MultiPaper:
    def __init__(self, title, paper_info_df,llm, paper_search_list=None, paper_table_list=None,lang='en'):
        self.llm = llm

        self.title = title
        # self.paper_info_list = paper_info_list

        head_list = [i for i in ['ID', 'Title', 'Abstract', 'Introduction', 'RelatedWork', 'Methodology',
                                 'Experiment', 'Discussion','Conclusion'] if i in paper_info_df.columns]
        self.paper_info_df = paper_info_df[head_list]
        language, _ = langid.classify(title)
        self.lang = lang
        # if language == 'en':
        #
        # else:
        #     self.lang = 'zh'
        self.paper_search_list = paper_search_list
        self.paper_table_list = paper_table_list
        self.point_table = None

        self.result_dict = OrderedDict()

    @staticmethod
    def df2string(df):

        doc = ''
        for val in df.values:
            if list(val).count(np.nan) == len(val)-2 or list(val).count("") == len(val)-2:
                # print('###############')
                # print(val)
                continue
            for head, text in zip(df.keys(), val):
                if text != np.nan or len(str(text))>3:
                    doc += f'# {head}\n{text}\n'
        # print('参考-资料：',doc)
        return doc

    def write_introduction(self, template):
        # 输入内容表，然后写一个背景
        print('开始写背景')
        if self.lang == 'en':
            draft_prompt = f'''
You are writing an introduction for a review paper, introducing the research background, research questions, importance of the research, and the purpose.

The title of the review is: `{self.title}`
References are: {self.df2string(self.paper_info_df)}

While writing, fully consider the references.
Writing guide, write according to the following four sections:
1. Write the background, often starting with the development of xxx...
2. Write the research motivation, explaining the necessity of the research, which could be filling a gap in existing research, resolving a controversy, testing a theory, or addressing a practical problem.
3. Write the purpose (specific research direction), clearly stating the main purpose or research question of the study.
4. The language should be professional, and the format should be consistent with the introduction of a paper.
5. Cite as many papers as possible. Citations in an article should be comprehensive and repetitive citations should be reduced.

Based on the references I provided, key research points from the references should be mentioned.

Here is a basic reference format: ```{template}```

Please ensure to follow the above steps, change the basic format if necessary, and the language should be rich and not monotonous, around 500 words.

The format for citing reference documents is: `<sup>id</sup><sup>id</sup>`, where ID is the paper ID I provided you. Example: Some content<sup>10</sup> some content<sup>20</sup><sup>30</sup>

# {self.title}
## Introduction:
'''
        else:
            draft_prompt = f'''
你在为一篇综述写一个引言，介绍研究的背景、研究问题、研究的重要性和目的。
综述的题目为:`{self.title}`
参考资料为:{self.df2string(self.paper_info_df)}
书写时充分考虑参考资料。
写作指导，按照以下四个章节书写：
1. 写出背景，多为随着xxx发展。。。
2. 写出研究动机，阐述研究的必要性，可能是填补现有研究的空白、解决一个争议、测试一个理论或者是应对实际问题。
3. 写出目的（具体的研究方向），明确地陈述研究的主要目的或研究问题。
4.语言专业，格式与论文引言格式一致。
5.尽可能多地引用论文,文章引用应该全面，减少重复引用.
根据我提供给你的参考资料，应该提到参考资料中的关键研究点。
以下是一个参考的基本格式:```{template}```
请确保按照以上步骤执行，必要时改变基本格式，语言应该丰富不呆板，500字左右。
引用参考文档的格式为:`<sup>id</sup><sup>id</sup>` ID 为我给你的论文ID。示例：一些内容<sup>10</sup>一些内容<sup>20</sup><sup>30</sup>

# {self.title}
## 引言：
'''
        draft = self.llm(draft_prompt)
        if self.lang == 'en':
            prompt = f'''
Draft:```{draft}```
Please refine the above draft into a professional introduction for a literature review paper. Retain the citation sources marked as <sup>ID1</sup><sup>ID2</sup>,like this:`some content.<sup>10</sup>some content<sup>20</sup><sup>30</sup>`.
The language should be professional yet engaging, with varied sentence structures to avoid a mechanical feel. Ensure the format is consistent with the introduction section of an academic paper.
Use varied sentence structures to make the expression more professional, without inventing new content, around 300 words.
'''
        else:
            prompt = f'''
草稿:```{draft}```
将以上草稿整理为专业的论文综述中的引言。保留引用源即<sup>ID1</sup><sup>ID2</sup>的内容/
要求语言专业但不呆板，句式多变，不要有机械感，格式符合论文中引言的格式。
句式变换使得表述更加专业，不要编造新的内容，300字左右。
'''
        draft = self.llm(prompt)
        self.result_dict['Introduction'] = draft
        return draft

    def get_point_table(self,text=''):

        if text:
            text = f'用户的分类请求为：{text}，如果用户请求合理，请按照用户的请求进行分类，如果不合理请说明不合理原因后进行分类'

        if self.point_table!=None and text=='':
            return  self.point_table
        # 根据论文信息整理出观点表
        if self.lang == 'en':
            prompt = f'''
I hope you can organize the references for the review article titled: `{self.title}`. 
Please categorize the references according to research topics related to the title. 
I will provide you with the references, and you should follow the format I give you and briefly summarize the research on this topic.

The references are:
```
{self.df2string(self.paper_info_df)}
```

Your response should be in the following format:
```
## Topic: xxx
Topic Summary: [Brief summary, requiring a higher level]
Sub-directions: [1.xxx, 2.xxx, 3.xxx]
## Topic: xxx
Topic Summary: [Brief summary, requiring a higher level]
Sub-directions: [1.xxx, 2.xxx, 3.xxx]
## Topic: xxx
Topic Summary: [Brief summary, requiring a higher level]
Sub-directions: [1.xxx, 2.xxx, 3.xxx]
...
```

First, classify the papers into 3-5 categories,
Ensure the categories align with the sub-directions under the review topic: `{self.title}`,
and provide a brief summary for each category.

{text}

Ensure that there are clear differences between the topics, and try to cover all the references. The topics and sub-topics should be clearly distinct but highly relevant to the review topic.

Please start summarizing:
'''
        else:
            prompt = f'''
我希望你整理一下参考资料，为：`{self.title}`这个综述整理文章，按照与题目相关研究主题进行分类，
我会给你参考资料，你按照我给你的格式，并对这个主题的研究进行简要概括。
参考资料为：
```
{self.df2string(self.paper_info_df)}
```
你回答的格式为:
```
## 主题:xxx
主题总结:[简要总结，要求层级较高]
子方向:[1.xxx,2.xxx,3.xxx]
## 主题:xxx
主题总结:[简要总结，要求层级较高]
子方向:[1.xxx,2.xxx,3.xxx]
## 主题:xxx
主题总结:[简要总结，要求层级较高]
子方向:[1.xxx,2.xxx,3.xxx]
...
```
先将以上论文分类成3-5个类别，
要求符合综述主题：`{self.title}`下的子方向 ,
对每个类别进行简要总结。
{text}
要求主题与主题之间要有差异，尽量覆盖所有的参考资料。
主题与子主题之间要有明显差异，但是都与综述主题高度相关。
请开始总结：
'''
        print('开始分析观点')
        self.point_table = llm(prompt)
        print('观点分析结束')

        return self.point_table

    def _write_methods(self):
        if self.lang == 'en':
            prompt = f'''
I am writing a literature review, and this section aims to provide a brief introduction to the topic of the paper.

Reference documents are:
{self.df2string(self.paper_info_df)}
Referenced technologies:
{self.point_table}
The topic of the paper is: {self.title}

Based on the above information, please write a brief introduction of about 200 words. The introduction should briefly describe the research principles and the current state of research on the topic so that readers can have a certain understanding of the topic and the referenced technologies.

The format for citing reference documents is: `<sup>id</sup><sup>id</sup>`, where ID is the paper ID I provided you. Example: Some content<sup>10</sup> some content<sup>20</sup><sup>30</sup>.

Citations in an article should be comprehensive and repetitive citations should be reduced.

Topic introduction: 
'''
        else:
            prompt = f'''
我正在书写一个论文综述，这次书写的部分为简单介绍一下论文主题。        
参考文档为:
{self.df2string(self.paper_info_df)}
参考的技术：
{self.point_table}
文章的主题为:{self.title}
请参考以上信息，写一段200字左右的介绍，简要介绍一下我主题的研究原理以及研究现状，使得读者能够对主题和参考技术有一定分的了解。
引用参考文档的格式为:`<sup>id</sup><sup>id</sup>` ID 为我给你的论文ID。示例：一些内容<sup>10</sup>一些内容<sup>20</sup><sup>30</sup>
文章引用应该全面，减少重复引用.
主题简介：
'''
        return self.llm(prompt)


    def get_methods_outline(self,template):
        if self.lang == 'en':
            prompt = f'''
You are writing an outline for the "Methodology" section of an article review, which mainly introduces different methods for the same topic in the reference document.
The overall requirements are as follows:
1. Write background information for each specific technical direction, describe the background information of the technology, and help readers understand the basic concepts and framework of the research field.
2. Systematically introduce the research progress and main findings of each field or topic, which requires very detailed writing. Each field or topic is divided into sections.
3. Strictly adhere to the topic of the article and only choose specific directions related to the topic for discussion, deepening all methods that can support the theme step by step, including relevant supporting research.

The theme of the article is: {self.title}

The reference document is:
```{self.df2string(self.paper_info_df)}```
The document sorted by direction is:
```{self.point_table}```

The user's outline template or requirements are:
```
{template}
```
Write according to the following requirements:

Outline reference:
```
Technical Introduction: This section refers to the reference document to introduce the article's topic technology
Direction 1
-Method Description 1
-Method Description 2
...
Direction 2
-Method Description 1
-Method Description 2
...
Direction 3
-Method Description 1
-Method Description 2
...

...
```
Requirements:
1. Adhere to the theme of the paper, referring to the sorted viewpoints and reference documents.
2. The outline should include two levels. Fully reference the literature, and when listing the outline, try to cover as much of the reference literature as possible.
3. You only need to introduce the outline of the methodology section, no other content is needed.
4. The direction needs to be highly summarized, while the description of the method comes second but should also have a certain degree of summary.

Output in the following format:''' + '''
---format---
<thought>According to requirement analysis</thought>
```json
[
{"section": "xxx",
   "sub_section": ["xxx", "xxx", "xxx", ...]},
  {'section': 'xxx',
   "sub_section": ["xxx", "xxx", "xxx", ...]},
  {"section": "xxx",
   "sub_section": ["xxx", "xxx", "xxx", ...]},
   ...
]
```
------
'''
        else:
            prompt = f'''
您正在撰写一篇文章评论的“方法”部分的大纲，该部分主要介绍参考文献中关于同一主题的不同方法。
总体要求如下：
1. 为每个具体技术方向写背景信息，描述该技术的背景信息，帮助读者了解研究领域的基本概念和框架。
2. 系统地介绍每个领域或主题的研究进展和主要发现，需要非常详细的写作。每个领域或主题分为几个部分。
3. 严格遵循文章的主题，只选择与主题相关的具体方向进行讨论,逐步深入所有可以支持主题的方法，包括相关的支持性研究。

文章的主题为:{self.title}

参考文档为:
```{self.df2string(self.paper_info_df)}```
文档按照方向整理后的结果为：
```{self.point_table}```

用户提供的大纲模板或要求为：
```
{template}
```
按照以下要求书写：

大纲参考：
```
技术介绍：本节参考文献介绍文章的主题技术
方向 1
-方法描述 1
-方法描述 2
...
方向 2
-方法描述 1
-方法描述 2
...
方向 3
-方法描述 1
-方法描述 2
...

...
```
要求：
1.符合论文主题，参考整理后的观点以及参考文献。
2.大纲应该包含两个层级。充分参考文献资料，列大纲的时候应该尽可能多覆盖参考文献。
3.你只需要介绍方法的大纲部分，不需要输出其他内容。
4. 方向应该高度总结，方法描述次之，但也要有一定的总结性

输出为以下格式：''' + '''
---format---
<thought>根据需求分析</thought>
```json
[
{"section": "xxx",
   "sub_section": ["xxx", "xxx","xxx",...]},
  {'section': 'xxx',
   "sub_section": ["xxx", "xxx","xxx",...]},
  {"section": "xxx",
   "sub_section": ["xxx", "xxx","xxx",...]},
   ...
]
```
------
'''

        print('开始写大纲')
        sections = super_eval(llm(prompt))
        print('大纲书写结束')
        return sections


    def get_topic_prompt(self,topic):
        if self.lang == 'en':
            prompt = f'''
You are writing a methodology section of an article review, which mainly introduces different methods for the same topic in the reference document.

The theme of the article is: {self.title}

The reference document is:
```{self.df2string(self.paper_info_df)}```
The organized document is:
```{self.point_table}```
The outline entered by the user is:
```{topic}```
Please write according to the following requirements:
1. Consider the relationship between the outline and the theme; Do not deviate from the theme.
2. Keep as many useful details as possible in the reference materials and thoroughly explain these details.
3. Only need to introduce the methodology section; Do not include any other content.
4. Fully cite literature and frequently use arguments from the literature. To ensure the professionalism of the paper, the document should be cited multiple times.
5. Write according to the outline provided by the user; Do not write content beyond the outline.
6. Considering the readers; Before introducing the methodology, provide a brief and slightly simplified technical background introduction.
7. The format for citing references should be:< sup>id</sup><sup>id</sup>， The ID is the reference ID I provided. Example: Some content<sup>10</sup>Some content<sup>20</sup><sup>30</sup>
If there are sufficient reference materials, use narrative mode to thoroughly introduce the literature.
9. Whenever possible, cite every sentence.Citations in an article should be comprehensive and repetitive citations should be reduced.
Please write according to the outline and reference materials, output directly in MD format, use professional academic language, transform sentence structure, and ensure language coherence without any limitations. Retain title:
'''
        else:
            prompt = f'''
你在写一篇文章综述的方法部分的，这部分主要介绍参考文档中相同主题的不同方法。

文章的主题为:{self.title}

参考文档为:
```{self.df2string(self.paper_info_df)}```
整理后的文档为：
```{self.point_table}```
用户输入的大纲为：
```{topic}```
请按照以下要求撰写：
1. 考虑提纲与主题之间的关系；不要偏离主题。
2. 尽可能保留参考资料中的有用细节，并彻底解释这些细节。
3. 只需要介绍方法论部分；不要包含其他内容。
4. 完全引用文献，频繁使用文献中的论点。为确保论文的专业性，应多次引用文档。
5. 根据用户提供的大纲编写；不要编写大纲以外的内容。
6. 考虑到读者；在介绍方法论之前，提供一个简短且稍微简化的技术背景介绍。
7. 引用参考文献的格式应为：<sup>id</sup><sup>id</sup>，其中ID是我提供的引用ID。示例：一些内容<sup>10</sup>一些内容<sup>20</sup><sup>30</sup>
8. 如果参考资料足够，采用叙事模式彻底介绍文献。
9. 尽可能每句话都进行引用,文章引用应该全面，减少重复引用。
请根据提纲和参考资料编写，直接以MD格式输出，使用专业的学术语言，变换句子结构，并确保语言连贯，不死板。保留标题，使用中文：
'''

        return prompt

    def write_methods(self, template):
        self.get_point_table()
        sections = self.get_methods_outline(template)
        draft = self._write_methods() # 写一个介绍无论如何都要写



        sub_prompt = []
        for inx in range(len(sections)):
            section = sections[inx]
            topic = ''
            topic += f"## {section['section']} \n"
            for sub_section in section['sub_section']:
                topic += f"### {sub_section} \n"

            if inx == 0 and re.search('Introduction',topic,re.IGNORECASE):
                continue

            prompt = self.get_topic_prompt(topic)
            sub_prompt.append(prompt)

        def get_draft(prompt):
            return self.llm(prompt)

        _draft_list = []
        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            # 提交所有任务
            future_to_prompt = {executor.submit(get_draft, prompt): prompt for prompt in sub_prompt}

            # 等待所有任务完成，并按顺序获取结果
            for future in concurrent.futures.as_completed(future_to_prompt):
                prompt = future_to_prompt[future]
                try:
                    _draft = future.result()
                    _draft_list.append(_draft)
                except Exception as exc:
                    print(f'{prompt} generated an exception: {exc}')

        # 保证顺序不打乱
        _draft_list_sorted = [None] * len(sub_prompt)
        for i, prompt in enumerate(sub_prompt):
            for future in future_to_prompt:
                if future_to_prompt[future] == prompt:
                    _draft_list_sorted[i] = future.result()

        _draft_list = _draft_list_sorted

        for _draft in _draft_list:

            if '```md' in _draft:
                _draft = re.findall('```.{0,1}md(.*?)```', _draft, re.DOTALL)
                _draft = '\n\n'.join(_draft)
            elif '```markdown' in _draft:
                _draft = re.findall('```.{0,1}markdown(.*?)```', _draft, re.DOTALL)
                _draft = '\n\n'.join(_draft)
            draft += f'{_draft}\n\n'
        self.result_dict['Methods'] = draft
        return draft

    def write_discussion(self, template):
        doc = ''

        for k, v in self.result_dict.items():
            doc += f'# {k}\n{v}\n\n'
        if self.lang == 'en':
            prompt = f'''
The reference document is:
```{self.df2string(self.paper_info_df)}```
Based on the reference documents, complete the discussion section of the review.
The theme of the article is: {self.title}
Discuss the above section in conjunction with reference documents.
The parts that need to be discussed:
--Methods--
{self.result_dict['Methods']}
----------
Please follow the steps below
1. Analyze the significance of each topic and discuss it in a very specific way, using the reference document I provided as evidence to support it.
2. Analyze the limitations of each topic and discuss them in a very specific manner, using the reference documents and evidence I provided to support them.
3. The results should be presented objectively, while pointing out the consistency and differences between different studies.
4. Identify the differences in the reference document, discuss the limitations in a very specific manner, and cite the evidence from the reference document I provided to support it.
5. Based on the results of the discussion, propose future research directions.
Writing requirements:
1. Refer to the documentation as much as possible and keep detailed explanations.
2. Refer to the description in the previous article and do not contradict it.
3. Language major, describe specific limitations.
4. Prohibit outputting content beyond the discussion
5. The format for referencing reference documents is:`< <sup>id</sup><sup>id</sup>` ID is the paper ID I gave you. Example: Some content<sup>10</sup>Some content<sup>20</sup><sup>30</sup>
6. Cite papers as much as possible,Citations in an article should be comprehensive and repetitive citations should be reduced.
You need to dig carefully from the materials, write multiple points according to the format of the paper review discussion, refer to the outline template, do not be lazy, and change the basic format if necessary. The language should be rich and not rigid, the sentence structure should be varied, around 2000 words, and output directly in MD format with a title.
'''
        else:
            prompt = f'''
参考文档为:
```{self.df2string(self.paper_info_df)}```        
结合参考文档，完成综述的讨论部分。
文章的主题为:{self.title}
对上面的部分进行讨论，结合参考文档。
需要讨论的部分：
```{self.result_dict['Methods']}```

一个可以参考的大纲模板为:
```{template}```

请按照以下步骤执行
1. 分析每个主题的意义，讨论意义应该非常具体，引用我给你的参考文档作为论据支撑。
2. 分析每个主题的局限性，讨论局限性应该非常具体，引用我给你的参考文档论据支撑。
3. 结果应该客观呈现，同时指出不同研究之间的一致性和差异。
4. 找到参考文档中的分歧，讨论局限性应该非常具体，引用我给你的参考文档论据支撑。
5. 基于讨论的结果对未来提出研究方向。
写作要求：
1.尽可能参考文档并且保留细节说明。
2.参考之前文章的描述，不与之前的文章产生矛盾。
3.语言专业，描述具体不死板。
4.禁止输出讨论以外的内容
5.引用参考文档的格式为:`<sup>id</sup><sup>id</sup>` ID 为我给你的论文ID。示例：一些内容<sup>10</sup>一些内容<sup>20</sup><sup>30</sup>
6.尽可能多引用论文,文章引用应该全面，减少重复引用
你需要细致的从材料中挖掘，按照论文综述的讨论的格式写多点，参考大纲模板，不要偷懒，必要时改变基本格式，语言应该丰富不呆板,句式多变，2000字左右，直接输出md格式有标题，使用中文。
'''

        draft = self.llm(prompt)
        if '```md' in draft:
            draft = re.search('```.{0,1}md(.*?)```', draft, re.DOTALL).group(1)
        elif '```markdown' in draft:
            draft = re.search('```.{0,1}markdown(.*?)```', draft, re.DOTALL).group(1)

        self.result_dict['Discussion'] = draft
        return draft

    def write_conclusion(self, template):

        doc = ''

        for k, v in self.result_dict.items():
            doc += f'# {k}\n{v}\n\n'
        if self.lang == 'en':
            prompt = f'''
The theme of the article is: {self.title}

Supplement and continue the conclusion section of the article review below.
Previous article: ` {doc}`

The overall requirements are:
1. Summarize the main findings and significance of the research.
2. It may include suggestions for practical applications or prospects for future research.
3. Fully refer to previous articles,Cite as many papers as possible,Citations in an article should be comprehensive and repetitive citations should be reduced.

Please follow the steps below to execute
1. Summarize the main findings, which include [xxx].
2. Discuss the significance of the research, that is, the significance of these findings is [xxx].
3. Provide practical application suggestions or future research prospects, that is, based on these findings, we suggest [xxx].

The basic format is: In this study, we explored the current situation of [topic] and analyzed in detail the [main analysis points]. We have found [a brief summary of the main findings]. These findings have significant implications for [field/practice] as [explanatory significance]. Despite the limitations mentioned, this study still provides new insights into the field/practice and points the way for future research.
Please ensure to follow the above steps and change the basic format if necessary. The language should be rich and not rigid, with around 300 words.
'''
        else:

            prompt = f'''
文章的主题为:{self.title}

补充和续写以下文章文章综述的结论部分。
之前文章：`{doc}`

总体要求为:
1. 总结研究的主要发现和研究的意义。
2. 可能包括对实践应用的建议或对未来研究的展望。
3. 充分参考之前的文章，尽可能多引用论文,文章引用应该全面，减少重复引用

请按照以下步骤执行
1. 总结主要发现，即：综合所有研究，主要发现包括[xxx]。
2. 讨论研究的意义，即：这些发现的意义是[xxx]。
3. 提出实践应用建议或未来研究展望，即：基于这些发现，我们建议[xxx]。

一个可以参考的基本格式为：{template}

请确保按照以上步骤执行，必要时改变基本格式，语言应该丰富不呆板，500字左右，使用中文。
'''

        draft = self.llm(prompt)
        if '```md' in draft:
            draft = re.search('```.{0,1}md(.*?)```', draft, re.DOTALL).group(1)
        elif '```markdown' in draft:
            draft = re.search('```.{0,1}markdown(.*?)```', draft, re.DOTALL).group(1)
        self.result_dict['Conclusion'] = draft
        return draft

    def paper_choice(self, paper_filter, min_score, max_paper):
        if max_paper >= len(self.paper_info_df):
            return self.paper_info_df
        df = self.paper_info_df
        # 添加"文档id"列，内容为从1开始的整数序列
        df['文档id'] = range(1, len(df) + 1)

        # 将"文档id"列移动到第一列
        cols = df.columns.tolist()
        cols = cols[-1:] + cols[:-1]
        df = df[cols]
        prompt = f'''
你需要给以下论文进行相关度打分，比较我的题目和论文的关系。
满分为10分，非常相关为7分以上，这部分指相同的研究方向。
一般相关为3-7分，通常为领域相同。
不相关为0-2分，
例如:题目强化学习在某领域的应用，同为强化学习，相同领域，7分以上
强化学习但是领域不同。5分左右
与机器学习相关3分
不相关0分。
---
我的题目为:{paper_filter}

论文介绍为：
{self.df2string(df)}

请仔细对比论文介绍和我的题目，并进行打分
请先写出思考过程，思考过程为：题目为：xxx，根据相关性排序后的文档顺序为xxx
然后把思考结果打分后按照以下json格式返回:
```json
[{{"文档id": Int,"Score":Int}},{{"文档id": Int,"Score":Int}}...]
```
思考过程和json为:
'''
        doc_score = self.llm_eval(prompt)
        print(doc_score)
        sorted_docs = sorted(doc_score, key=lambda x: x['Score'], reverse=True)
        ids = [i['文档id'] for i in sorted_docs if i['Score'] > min_score]
        ids = ids[:max_paper]
        print(ids)

        df2 = df[df['文档id'].isin(ids)]
        print(df2)
        self.paper_info_df = df2
        return df2


